﻿const express      = require('express');
const logger       = require('morgan');
const bodyParser   = require('body-parser');
const {expressjwt} = require('express-jwt');
const cors         = require('cors');
// Set up the express app
const app = express();

// Log requests to the console.
app.use(logger('dev'));

app.use(bodyParser.json({limit: "50000kb"}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(function (req, res, next) {
     //跨域处理
     res.setHeader('Access-Control-Allow-Origin', '*');  //允许任何源
     res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');  
     res.setHeader('Access-Control-Allow-Headers', '*');   //允许任何类型
     // res.writeHead(200, {"Content-Type": "text/plain;charset=utf-8"});  
    next();  //next 方法就是一个递归调用
});

app.use(cors());

// app.use(expressjwt({
//     secret: 'kg_admin',
//     algorithms:['HS256'],
//     credentialsRequired:true,//对不带Token的请求也进行解析和抛出异常，如果是false，不会对没有token的请求进行解析和抛出异常
//     getToken: function(req){
//         let token = req.headers.authorization.split(' ')[1]
//         return token
//     }
// }).unless({
//     path: [
//         '*',
//         '/api/v1/user/register',
//         '/api/v1/user/login',
//         '/api/v1/user/register',
//         '/api/v1/user/login',
//         '/api/v1/addPoint',
//         '/api/v1/getPoint',
//         '/api/v1/Point/:id',
//         { url: '/api/v1/Point', methods: ['DELETE',  'POST'] },
// 		{ url: '/api/v1/maplayertree', methods: ['GET',  'POST'] },
//         { url: /^\/api\/v1\/maplayertree\/.*/, methods: ['GET', 'PATCH', 'DELETE'] }
//     ]  //白名单,除了这里写的地址，其他的URL都需要验证token
// }));

app.use(function (err, req, res, next) {
    if (err.name === 'UnauthorizedError') {
        res.status(401).send({
            success: false,
            code: 401,
            message: 'No Authorization'
        })
    }
});

require('./server/routes/user')(app);
require('./server/routes/pipePoint')(app);
require('./server/routes/drawLine')(app);
require('./server/routes/drawPolygon')(app);
require('./server/routes/importShp')(app);

app.get('*', (req, res) => res.status(200).send({
    message: 'Welcome to the beginning of nothingness.',
}));

module.exports = app;